package com.zrf.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author zhanrf
 * @Date 2022/1/5 0:04
 */
@EnableRabbit
@Configuration
public class WareRabbitMqConfig {

	/** 延迟队列名字 */
	private static final String STOCK_DELAY_QUEUE_NAME = "stock.delay.queue";
	/** 死信队列名字 */
	private static final String STOCK_RELEASE_QUEUE_NAME = "stock.release.stock.queue";
	/** 交换机名字 */
	private static final String STOCK_EVENT_EXCHANGE_NAME = "stock-event-exchange";

	/**
	 * 使用JSON序列化机制，进行消息转换
	 */
	@Bean
	public MessageConverter messageConverter() {
		return new Jackson2JsonMessageConverter();
	}

	@Bean
	public TopicExchange stockEventExchange() {
		return ExchangeBuilder.topicExchange(STOCK_EVENT_EXCHANGE_NAME).build();
	}

	/**
	 * 死信队列
	 */
	@Bean
	public Queue stockReleaseStockQueue() {
		return QueueBuilder.durable(STOCK_RELEASE_QUEUE_NAME).build();
	}


	/**
	 * 延迟队列
	 */
	@Bean
	public Queue stockDelay() {
		return QueueBuilder.durable(STOCK_DELAY_QUEUE_NAME)
				.deadLetterExchange(STOCK_EVENT_EXCHANGE_NAME)
				.deadLetterRoutingKey("stock.release")
				.ttl(120000).build();
	}


	/**
	 * 交换机与死信队列绑定
	 */
	@Bean
	public Binding stockLocked() {
		return BindingBuilder.bind(stockReleaseStockQueue()).to(stockEventExchange()).with("stock.release.#");
	}

	/**
	 * 交换机与延迟队列绑定
	 */
	@Bean
	public Binding stockLockedBinding() {
		return BindingBuilder.bind(stockDelay()).to(stockEventExchange()).with("stock.locked");
	}

}
